package com.am.meeting.utils;


import com.am.meeting.config.RedissonConfig;
import com.am.meeting.constants.RedisConstants;
import org.redisson.Redisson;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.SecureRandom;
@Component
public class MeetingNumberGenerator {
    private static final int MEETING_NUMBER_LENGTH = 6;
    private static final int MAX_NUMBER = (int) Math.pow(10, MEETING_NUMBER_LENGTH);
    private static final SecureRandom secureRandom = new SecureRandom();

    @Resource
    RedissonClient redissonClient;
    /**
     * 生成 6 位数的唯一会议号
     * @return 6 位数的唯一会议号字符串
     */
    public  String generateMeetingNumber() {
        String meetingNumber;
        do {
            int randomNumber = secureRandom.nextInt(MAX_NUMBER);
            meetingNumber = String.format("%0" + MEETING_NUMBER_LENGTH + "d", randomNumber);
            RBucket<String> bucket = redissonClient.getBucket(RedisConstants.MEETING_NUMBERS_KEY + meetingNumber);
            // 使用 trySet 方法尝试设置会议号，若已存在则返回 false
        } while (!redissonClient.getBucket(RedisConstants.MEETING_NUMBERS_KEY + meetingNumber).trySet("1"));
        return meetingNumber;
    }

}